package com.ruoyi.web.controller.system;

import java.lang.reflect.Array;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;

import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.GsonUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.Ali404UserService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.ali404.UserInfo;
import nl.basjes.parse.useragent.UserAgent;
import nl.basjes.parse.useragent.UserAgentAnalyzer;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;



    @Autowired
    private ISysUserService userService;

    @Autowired
    private Ali404UserService ali404Service;

    private  Gson gson=new Gson();


    UserAgentAnalyzer uaa = UserAgentAnalyzer
            .newBuilder()
            .hideMatcherLoadStats()
            .withCache(10000)
            .build();
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(HttpServletRequest requests, @RequestBody LoginBody loginBody)
    {
        String userAgent = requests.getHeader("user-agent");
        UserAgent agent = uaa.parse(userAgent);
        String cls =agent.get("OperatingSystemClass").getValue();
        String win =agent.get("OperatingSystemName").getValue();

        System.out.println("用户："+loginBody.getUsername()+"登录  系统:"+win+" 设备:"+cls);


            if(!"admin".equals(loginBody.getUsername())){

                if(win.indexOf("Windows")==-1||cls.indexOf("Desktop")==-1){
                    AjaxResult ajax = AjaxResult.error("内测版本目前仅支持Win系统登录");
                    return ajax;
                }

                String loginStr="https://www.ali404.com/wp-json/jwt-auth/v1/token";

                String resJson="";
                String tokens="";
                try {
                    OkHttpClient client = new OkHttpClient().newBuilder()
                            .build();
                    MediaType mediaType = MediaType.parse("text/plain");
                    okhttp3.RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                            .addFormDataPart("username",loginBody.getUsername())
                            .addFormDataPart("password",loginBody.getPassword())
                            .build();
                    Request request = new Request.Builder()
                            .url("https://www.ali404.com/wp-json/jwt-auth/v1/token")
                            .method("POST", body)
                            .addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)")
                            .build();
                    Response response = client.newCall(request).execute();

                    resJson=response.body().string();


                    String b2_token=response.headers("Set-Cookie").toString();
                    tokens= b2_token.substring(b2_token.indexOf("b2_token")+9,b2_token.indexOf(";")).trim();

                 }catch (Exception e){

                }




                 UserInfo AliUserInfo =  gson.fromJson(resJson,UserInfo.class);

                System.out.println("AliUserInfo:"+gson.toJson(AliUserInfo));

                if(AliUserInfo.getId()==null){
                    AjaxResult ajax = AjaxResult.error("用户不存在/密码错误");
                    return ajax;
                }else {
                    Integer id = AliUserInfo.getId();
                    try {


                        Integer isbuy = ali404Service.getAiTools(Long.parseLong(AliUserInfo.getId()+""));
                        System.out.println("isbuy:"+isbuy);
                        if(isbuy==0){
                            AjaxResult ajax = AjaxResult.error("无权限访问,请先兑换客户端!");
                            return ajax;
                        }


                    }catch (Exception e){

                    }




                    SysUser user = userService.selectUserByAliId(Long.parseLong(id + ""));
                    if (user == null) {
                        System.out.println("不存在本地注册 id：" + id);


                        SysUser addUser = new SysUser();

                        Long[] PostIds={1L};
                        Long[] RoleIds={100L};

                        addUser.setPassword(SecurityUtils.encryptPassword(AliUserInfo.getUser_code()+"3iitUvxwLaCs99mY"));
                        addUser.setPostIds(PostIds);

                        addUser.setNickName(AliUserInfo.getName());
                        addUser.setDeptId(101L);
                        addUser.setAvatar(AliUserInfo.getAvatar());
                        addUser.setUserName(AliUserInfo.getUser_code());
                        addUser.setCreateBy(AliUserInfo.getId()+"");
                        addUser.setRoleIds(RoleIds);
                        addUser.setStatus("0");

                        userService.insertUser(addUser);

                        AjaxResult ajax = AjaxResult.success();
                        // 生成令牌
                        String token = loginService.login(AliUserInfo.getUser_code(), AliUserInfo.getUser_code()+"3iitUvxwLaCs99mY", loginBody.getCode(),
                                loginBody.getUuid());

                        ajax.put(Constants.TOKEN, token);
                        return ajax;

                    }else{
                        System.out.println("有账号");
                        //本地已经有账号
                        AjaxResult ajax = AjaxResult.success();
                        // 生成令牌
                        String token = loginService.login(AliUserInfo.getUser_code(), AliUserInfo.getUser_code()+"3iitUvxwLaCs99mY", loginBody.getCode(),
                                loginBody.getUuid());

                        ajax.put(Constants.TOKEN, token);
                        return ajax;

                    }

                }
            }

                AjaxResult ajax = AjaxResult.success();
                // 生成令牌
                String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                        loginBody.getUuid());

                ajax.put(Constants.TOKEN, token);
                return ajax;




    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
